package com.tiny.controller;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.tiny.model.Role;
import com.tiny.model.RolePermission;

public class RoleController extends Controller {

	public void index() {
		render("/frame/role.html");
	}
	
	public void query(){
		StringBuilder sql = new StringBuilder(" from role where 1=1 ");

		if (StrKit.notBlank(this.getPara("role_name"))) {
			sql.append(String.format(" and role_name like '%s%%' ",
					this.getPara("role_name")));
		}
		
		if (StrKit.notBlank(this.getPara("sort"))) {
			sql.append(String.format("%s %s %s", "order by",this.getPara("sort"),this.getPara("order")));
		}
		else{
			sql.append(" order by id desc ");
		}
		
		Page<Role> page = Role.dao.paginate(this.getParaToInt("page"), this.getParaToInt("rows"),"select * ", sql.toString());
		
		renderJson(page.getList());
	}
	
	public void save(){
		Role role = getModel(Role.class);
		
		role.set("role_name", this.getPara("role_name"));
		role.set("description", this.getPara("description"));

		setAttr("success", role.save());
		renderJson();
	}
	
	public void edit(){
		Role role = getModel(Role.class);
		
		role.set("role_name", this.getPara("role_name"));
		role.set("description", this.getPara("description"));
		role.set("id", this.getPara("id"));

		setAttr("success", role.update());
		renderJson();
	}

	public void remove(){
		setAttr("success", Role.dao.deleteById(this.getPara("id")));
		renderJson();
	}
	
	public void managePermission(){
		Db.update(" delete from RolePermission where role_id=? ",this.getPara("id"));
		Integer[] pids=this.getParaValuesToInt("permission_id");
		for(Integer id:pids){
			RolePermission rp=new RolePermission();
				rp.set("role_id", this.getPara("id"));
				rp.set("permission_id", id);
				setAttr("success", rp.save());
		}
		renderJson();
	}

	public void getPermissions(){
		renderJson(Db.find(" select permission_id as id from RolePermission where role_id=? ",this.getPara("id")));
	}
	
	public void allRoles(){
		renderJson(Db.find(" select id,role_name as text from Role "));
	}
}